package com.whmnx.chitchat.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.app.FragmentManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.microsoft.signalr.HubConnection;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack;
import com.tencent.qcloud.tim.uikit.component.AudioPlayer;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.component.action.PopMenuAction;
import com.tencent.qcloud.tim.uikit.component.video.CameraActivity;
import com.tencent.qcloud.tim.uikit.component.video.JCameraView;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.inputmore.InputMoreFragment;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfoUtil;
import com.tencent.qcloud.tim.uikit.utils.BackgroundTasks;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.tencent.qcloud.tim.uikit.utils.TUIKitLog;
import com.whmnx.chitchat.R;
import com.whmnx.chitchat.adapter.MessageListAdapter2;
import com.whmnx.chitchat.base.BaseFragment;
import com.whmnx.chitchat.bean.ChatDetailsBean;
import com.whmnx.chitchat.bean.ChatDtssBean;
import com.whmnx.chitchat.bean.LoginBean;
import com.whmnx.chitchat.bean.MessagePackBean;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.event.EventConstants;
import com.whmnx.chitchat.event.MessageEvent;
import com.whmnx.chitchat.http.CallBack;
import com.whmnx.chitchat.http.HttpClient;
import com.whmnx.chitchat.main.MainActivity;
import com.whmnx.chitchat.ui.book.GroupMeberActivity;
import com.whmnx.chitchat.ui.chat.ChatActivity;
import com.whmnx.chitchat.ui.chat.ChatSettingActivity;
import com.whmnx.chitchat.ui.chat.model.UserModel;
import com.whmnx.chitchat.utils.FileDownUtil;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;
import com.whmnx.chitchat.view.ChatLayout;
import com.whmnx.chitchat.view.MessageLayout;
import com.whmnx.chitchat.view.ShowImagesDialog;
import com.whmnx.chitchat.view.input.InputLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * author : huang
 * date   : 2020/7/21 0021 17:58
 * version: 1.0
 * @author Administrator
 */
public class ChatFragment3 extends BaseFragment {
    public  ChatLayout mChatLayout;
    public ChatInfo mChatInfo;
    private TitleBarLayout mTitleBar;
    private List<UserModel> mContactList = new ArrayList<>();
    private InputLayout inputLayout;
    private RelativeLayout rlHead;
    private ImageButton ib_back,ibRight;
    private TextView headTitle,tvNotice;
    private EditText chat_message_input;
    private Button mSendAudioButton;

    private RecyclerView rvChatDetails;

    private AnimationDrawable mVolumeAnim;

    private MessageListAdapter2 messageListAdapter2;
    protected Activity mActivity;

    private List<ChatDetailsBean> mDataSource = new ArrayList<>();
    private List<ChatDetailsBean> mDataMiMiSource = new ArrayList<>();
    private List<ChatDetailsBean> mDataSource2 = new ArrayList<>();
    public List<String> imgList = new ArrayList<>();
    public List<String> imgList2 = new ArrayList<>();

    public HubConnection hubConnection;
    //是否连接成功
    public boolean isConnect;

    private InputLayout.MessageHandler mMessageHandler;
    private FragmentManager mFragmentManager;
    private InputMoreFragment mInputMoreFragment;
    private boolean mSendEnable;
    private boolean mAudioCancel;
    private int mCurrentState;
    private int mLastMsgLineCount;
    private float mStartRecordY;
    private String mInputContent;

    private String[] split;
    private int string;

    protected List<PopMenuAction> mPopActions = new ArrayList<>();
    protected List<PopMenuAction> mMorePopActions = new ArrayList<>();
    private boolean sendMegFlag = false;
    private String batchID;
    private SmartRefreshLayout refresh;

    private int page = 1;
    private int Rows = 20;
    private ChatDtssBean result2;
    private int page2;


    @Override
    protected int getLayoutResource() {
        return R.layout.chat_fragment;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = (ChatActivity) getContext();
        Bundle bundle = getArguments();
        mChatInfo = (ChatInfo) bundle.getSerializable(Constants.CHAT_INFO);
        mChatLayout = rootView.findViewById(R.id.chat_layout);
        rvChatDetails = rootView.findViewById(R.id.rv_chat_details);

        rlHead = rootView.findViewById(R.id.rl_head);
        ib_back = rootView.findViewById(R.id.ib_back);
        headTitle = rootView.findViewById(R.id.head_title);
        ibRight = rootView.findViewById(R.id.ib_right);
        tvNotice = rootView.findViewById(R.id.tv_notice);

        refresh = rootView.findViewById(R.id.refreshLayout);


        LinearLayoutManager linearLayoutManager =  new LinearLayoutManager(getActivity());
        //  linearLayoutManager.setStackFromEnd(true);
        mChatLayout.getMessageLayout().setLayoutManager(linearLayoutManager);
        mChatLayout.getMessageLayout().setItemAnimator(new DefaultItemAnimator());
        //密聊
        if (mChatInfo.isTopChat()){
            messageListAdapter2 = new MessageListAdapter2(getActivity(), mDataMiMiSource);
        }else {
            messageListAdapter2 = new MessageListAdapter2(getActivity(), mDataSource);
        }

      //  getConnection();
        initView();
        //得到聊天数据
        getChatRecordDetail(true);

        refresh.setOnRefreshListener(refreshLayout -> getChatRecordDetail(true));
        refresh.setOnLoadMoreListener(refreshLayout -> getChatRecordDetail(false));

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent messageEvent) {
        if (messageEvent.getMessageKey() != null) {
            if (messageEvent.getMessageKey().equals(EventConstants.DELMSG)) {
                getChatRecordDetail(true);
                //发送图片消息
            } else if (messageEvent.getMessageKey().equals(EventConstants.SENDIMG)) {
                String url = messageEvent.getMessageValue();
                split = url.split("—");
                string = Integer.parseInt(split[1]);
                //自己发
                sendMsg(mChatInfo, split[0]);
            }else if (messageEvent.getMessageKey().equals(EventConstants.ACCEPTMSG)){
                try {
                    MessagePackBean msgJosn = (MessagePackBean)messageEvent.getMessageKey2();
                  //  JSONObject jsonObject = new JSONObject(msgJosn);
                    String s = msgJosn.getMessage();
                    //发送者
                    String sendId = msgJosn.getSendId();
                    String groupId = msgJosn.getGroupID();
                    //0 消息类型
                    int type = msgJosn.getType();
                    //密聊 1，
                    int RecordType = msgJosn.getRecordType();
                    ChatDetailsBean chatDetailsBean = new ChatDetailsBean();
                    chatDetailsBean.setChatRecord_Content(s);
                    //消息类型
                    chatDetailsBean.setChatRecord_Type(type);
                    //私密
                    chatDetailsBean.setChatRecord_RecordType(RecordType);
                    String t = String.valueOf(System.currentTimeMillis() / 1000);
                    chatDetailsBean.setCreateTime(UItils.timeStamp2Date(t));
                    //发送人
                    chatDetailsBean.setChatRecord_SendUserID(sendId);
                    String receiveId = msgJosn.getReceiveId();
                    //接收人id
                    if (TextUtils.isEmpty(groupId) || groupId.contains("null")) {
                        chatDetailsBean.setChatRecord_UserID(receiveId);
                        if (mChatInfo.getId().equals(sendId)) {
                         //   UItils.playRingTone();
                            if (RecordType == 0){
                                mDataSource.add(chatDetailsBean);
                            }else {
                                mDataMiMiSource.add(chatDetailsBean);
                            }
                                messageListAdapter2.notifyDataSourceChanged(3, 0);
                                MessageEvent messageEvent2 = new MessageEvent();
                                messageEvent2.setMessageKey(EventConstants.SENDMSG);
                                EventBus.getDefault().post(messageEvent2);
                                getUpdateChatRecordState();
                        }
                    } else {
                        chatDetailsBean.setChatRecord_GroupID(groupId);
                        if (mChatInfo.getId().equals(groupId)){
                          //  UItils.playRingTone();
                             String id = SPUtil.getString(Constants.USERID);
                            if (!sendId.equals(id)) {
                                if (RecordType == 0){
                                    mDataSource.add(chatDetailsBean);
                                }else {
                                    mDataMiMiSource.add(chatDetailsBean);
                                }
                                messageListAdapter2.notifyDataSourceChanged(3, 0);
                                MessageEvent messageEvent2 = new MessageEvent();
                                messageEvent2.setMessageKey(EventConstants.SENDMSG);
                                EventBus.getDefault().post(messageEvent2);
                                getUpdateChatRecordState();
                            }
                        }
                    }

                    //  messageListAdapter2.notifyItemInserted(0);
                    //  updateMsgList(s);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if (messageEvent.getMessageKey().equals(EventConstants.ADDGROUP2)){
                  mActivity.finish();
                //是否发送成功
            }else if (messageEvent.getMessageKey().equals(EventConstants.ACCEPTMSG2)){
                try {
                    MessagePackBean msgJosn = (MessagePackBean)messageEvent.getMessageKey2();
                  //  JSONObject jsonObject = new JSONObject(msgJosn);
                    int status = msgJosn.getState();
                    String msg = msgJosn.getMessage();
                   // JSONObject jsonData = jsonObject.getJSONObject("Result");
                    String uID = msgJosn.getID();
                       if (TextUtils.isEmpty(uID)){
                        return;
                    }
                    //发送成共  接收
                        if (status == 1) {
                            if (uID.equals(mDataSource2.get(0).getID())) {
                                sendMegFlag = true;
                                mDataSource2.get(0).setStatus(com.whmnx.chitchat.constants.MessageInfo.MSG_STATUS_NORMAL);
                                if (mChatInfo.isTopChat()){
                                    mDataMiMiSource.set(mDataMiMiSource.size() - 1,mDataSource2.get(0));
                                   // messageListAdapter2.notifyDataSourceChanged(4, mDataMiMiSource.size()-1);
                                }else {
                                    mDataSource.set(mDataSource.size() - 1,mDataSource2.get(0));
                                  //  messageListAdapter2.notifyDataSourceChanged(4, mDataSource.size()-1);
                                }
                                messageListAdapter2.notifyDataSourceChanged(0,0);

                                //刷新消息列表
                                MessageEvent messageEvent2 = new MessageEvent();
                                messageEvent2.setMessageKey(EventConstants.SENDMSG);
                                EventBus.getDefault().post(messageEvent2);
                            }
                        } else {
                            /*if (!msg.contains("好友信息")) {
                               // UItils.showToastSafe(msg);
                            }else {
                                return;
                            }*/
                            //发送失败
                            if (uID.equals(mDataSource2.get(0).getID())) {
                                mDataSource2.get(0).setStatus(com.whmnx.chitchat.constants.MessageInfo.MSG_STATUS_NORMAL);
                                if (mChatInfo.isTopChat()) {
                                    mDataMiMiSource.set(mDataMiMiSource.size() - 1, mDataSource2.get(0));
                                    // messageListAdapter2.notifyDataSourceChanged(4, mDataMiMiSource.size()-1);
                                } else {
                                    mDataSource.set(mDataSource.size() - 1, mDataSource2.get(0));
                                    //  messageListAdapter2.notifyDataSourceChanged(4, mDataSource.size()-1);
                                }
                                messageListAdapter2.notifyDataSourceChanged(0, 0);
                            }

                      /*  if (mChatInfo.isTopChat()){
                            mDataMiMiSource.remove(mDataSource2);
                        }else {
                            mDataSource.remove(mDataSource2);
                        }*/
                        }
                        //  messageListAdapter2.notifyItemInserted(0);
                        //   messageListAdapter2.notifyDataSourceChanged(3, 0);
                    } catch(Exception e){
                        e.printStackTrace();
                    }
            }else if (messageEvent.getMessageKey().equals(EventConstants.NICKNAME)){
                String groupName = messageEvent.getMessageValue();
                headTitle.setText(groupName);
            }else if (messageEvent.getMessageKey().equals(EventConstants.NICKPOP)){
                String groupName = messageEvent.getMessageValue();
                mTitleBar.getMiddleTitle().setText(groupName);
                mChatInfo.setChatName(groupName);
            }else if (messageEvent.getMessageKey().equals(EventConstants.IMG)){
                List<String> myList = (List<String>) messageEvent.getMessageKey2();
                int pos = messageEvent.getMessageKey3();
                  ShowImagesDialog showImagesDialog = new ShowImagesDialog(mActivity, myList, pos);
                  showImagesDialog.show();
            }else if (messageEvent.getMessageKey().equals(EventConstants.CHOHUN)){ //撤回  主动
                  // getChatRecordDetail(true);
            }else if (messageEvent.getMessageKey().equals(EventConstants.CHOHUN2)){ //群成员/被动接收人 监听方法  撤回消息
                MessagePackBean messagePackBean =(MessagePackBean)messageEvent.getMessageKey2();
                batchID = messagePackBean.getBatchID();
               // getChatRecordDetail(true);

                for (ChatDetailsBean chatDetailsBean : result2.List) {
                    if (!TextUtils.isEmpty(batchID)){
                        if (batchID.equals(chatDetailsBean.getChatRecord_Batch())){
                            if (mChatInfo.isTopChat()){
                                mDataMiMiSource.remove(chatDetailsBean);
                            }else {
                                mDataSource.remove(chatDetailsBean);
                            }
                        }
                    }
                }
                messageListAdapter2.notifyDataSetChanged();
            }
        }
    }


    private void initView() {
        // TODO 通过api设置ChatLayout各种属性的样例
        // 单聊面板的默认 UI 和交互初始化
        mChatLayout.initDefault();
        mChatLayout.setChatInfo(mChatInfo);
        // TODO 通过api设置ChatLayout各种属性的样例
      //   ChatLayoutHelper.customizeChatLayout(getActivity(), mChatLayout);
        // 从 ChatLayout 里获取 InputLayout
        inputLayout = mChatLayout.getInputLayout();
     //   mChatLayout.getMessageLayout().setAdapter(messageListAdapter2);

        //获取单聊面板的标题栏
        mTitleBar = mChatLayout.getTitleBar();
     //   mTitleBar.setVisibility(View.GONE);
        headTitle.setText(mChatInfo.getChatName());
        //返回键
        ib_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mTitleBar.getRightGroup().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mChatInfo.getType() == TIMConversationType.Group) {
                    startActivity(new Intent(getActivity(), GroupMeberActivity.class).putExtra("Group_ID",mChatInfo.getId()));
                }else {
                    startActivity(new Intent(getActivity(), ChatSettingActivity.class).putExtra("chatInfo", mChatInfo));
                }
            }
        });

        ImageView voice_input_switch = inputLayout.findViewById(R.id.voice_input_switch);
        ImageView mMoreInputButton = inputLayout.findViewById(R.id.more_btn);
        mTitleBar.setBackgroundColor(getResources().getColor(R.color.white_color));
        mTitleBar.getMiddleTitle().setTextSize(18);
        mTitleBar.getMiddleTitle().setMaxLines(1);
        mTitleBar.getMiddleTitle().setEllipsize(TextUtils.TruncateAt.END);
        mTitleBar.getLeftIcon().setImageResource(R.mipmap.back);
        mTitleBar.getRightIcon().setImageResource(R.mipmap.chat);
        mTitleBar.getRightIcon().setMaxHeight(50);
        mTitleBar.getRightIcon().setMaxWidth(50);

       mTitleBar.getRightIcon().setOnClickListener(v -> {
            if (mChatInfo.getType() == TIMConversationType.Group) {
                startActivity(new Intent(getActivity(), GroupMeberActivity.class).putExtra("Group_ID",mChatInfo.getId()));
            }else {
                startActivity(new Intent(getActivity(), ChatSettingActivity.class).putExtra("chatInfo", mChatInfo));
            }
        });
        //  Button send_btn = inputLayout.findViewById(R.id.send_btn);
        // 从 ChatLayout 里获取 MessageLayout

        // 设置头像圆角，不设置则默认不做圆角处理
        //   messageLayout.setAvatarRadius(10);
        // 设置头像大小
        //   messageLayout.setAvatarSize(new int[]{45, 45});

        // 设置自己聊天气泡的背景
        //  messageLayout.setRightBubble(getActivity().getResources().getDrawable(R.drawable.chat_opposite_bg));
        // 设置朋友聊天气泡的背景
        //  messageLayout.setLeftBubble(context.getResources().getDrawable(R.drawable.chat_self_bg));

        //   EditText chat_message_input = inputLayout.findViewById(R.id.chat_message_input);

        if (mChatInfo.getType() == TIMConversationType.Group) {
            rlHead.setVisibility(View.VISIBLE);
            mTitleBar.setVisibility(View.GONE);
            ib_back.setOnClickListener(v -> getActivity().finish());
            ibRight.setOnClickListener(v -> {
                if (mChatInfo.getType() == TIMConversationType.Group) {
                    startActivity(new Intent(getActivity(), GroupMeberActivity.class).putExtra("Group_ID",mChatInfo.getId()));
                }
            });

            tvNotice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(getActivity(), GroupMeberActivity.class).putExtra("Group_ID",mChatInfo.getId()));
                }
            });
        } else {
            rlHead.setVisibility(View.GONE);
            tvNotice.setVisibility(View.GONE);
            mTitleBar.setVisibility(View.VISIBLE);
        }

        //表情
        ImageView face_btn = inputLayout.findViewById(R.id.face_btn);
        //发送按钮
        Button send_btn = inputLayout.findViewById(R.id.send_btn);

         mSendAudioButton = inputLayout.findViewById(R.id.chat_voice_input);
        //输入框
        chat_message_input = inputLayout.findViewById(R.id.chat_message_input);

        //隐藏表情
      //  face_btn.setVisibility(View.GONE);

        // 隐藏拍照并发送
        inputLayout.disableCaptureAction(true);
        // 隐藏发送文件
        inputLayout.disableSendFileAction(true);

        // 隐藏发送图片
        inputLayout.disableSendPhotoAction(true);

        // 隐藏发送文件
      //  inputLayout.disableSendFileAction(true);
        // 隐藏摄像并发送
        inputLayout.disableVideoRecordAction(true);

        // 可以用自定义的 fragment 来替换更多功能
        inputLayout.replaceMoreInput(new CustomInputFragment(mActivity));

        //单聊面板标记栏返回按钮点击事件，这里需要开发者自行控制
      //  mTitleBar.setOnLeftClickListener(view -> getActivity().finish());
        mTitleBar.setOnLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //普通消息 0   密聊消息是 1
                if (mChatInfo.isTopChat()){
                    Map<String, Object> params = new HashMap<>();
                    params.put("UserID", SPUtil.getString(Constants.USERID));
                    params.put("ToUserID",mChatInfo.getId());
                    params.put("RecordType","1");
                    HttpClient.get(getActivity(), Constants.GETDELETECHATRECORD, params,new CallBack<LoginBean>() {
                        @Override
                        public void onSuccess(LoginBean result) {
                            MessageEvent messageEvent = new MessageEvent();
                            messageEvent.setMessageKey(EventConstants.DELMSG);
                            EventBus.getDefault().post(messageEvent);
                        }
                    });
                }

                mActivity.finish();
            }
        });
        //发送按钮
        send_btn.setOnClickListener(v -> {
            String input = chat_message_input.getText().toString().trim();
            string = 0;
            sendMsg(mChatInfo, input);
        });


       mChatLayout.getMessageLayout().addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                 inputLayout.hideSoftInput();
                 return false;
            }

            @Override
            public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {

            }

            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

            }
        });

        mChatLayout.getMessageLayout().setPopActionClickListener(new MessageLayout.OnPopActionClickListener() {
            @Override
            public void onCopyClick(int position, ChatDetailsBean msg) {
                ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);
                if (clipboard == null || msg == null) {
                    return;
                }
                String con = msg.getChatRecord_Content();
                ClipData clip = ClipData.newPlainText("message", con);
                clipboard.setPrimaryClip(clip);
            }

            @Override
            public void onSendMessageClick(ChatDetailsBean msg, boolean retry) {
                String[] split = msg.getChatRecord_Content().split("##");
                if (split.length > 0) {
                    if (msg.getChatRecord_Type() == 3) {
                        UItils.showToastSafe("正在下载中...");
                        FileDownUtil.downloadAPK(split[0], split[1]);
                    }else {
                        Glide.with(mActivity).load(split[0]).into(new SimpleTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                FileDownUtil.saveToSystemGallery(mActivity,FileDownUtil.drawableToBitmap(resource));
                            }
                        });
                    }
                }
            }

            //删除消息
            @Override
            public void onDeleteMessageClick(int position, ChatDetailsBean msg) {
                //  deleteMessage(position, msg);
                Map<String, Object> params2 = new HashMap<>();
                params2.put("ChatRecordIDs",msg.getChatRecord_ID());
                params2.put("UserID", SPUtil.getString(Constants.USERID));
                HttpClient.get(getActivity(), Constants.GETDELETECHATRECORD, params2,new CallBack<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean result) {
                        if (mChatInfo.isTopChat()){
                            mDataMiMiSource.remove(msg);
                        }else {
                            mDataSource.remove(msg);
                        }
                        messageListAdapter2.notifyDataSetChanged();
                    }
                });

               /* Map<String, Object> params = new HashMap<>();
                params.put("UserID", SPUtil.getString(Constants.USERID));
                params.put("Page", "1");
                params.put("Rows", "100");
                //密聊
                if (mChatInfo.isTopChat()){
                    params.put("RecordType", "1");
                }else {
                    params.put("RecordType", "0");
                }

                if (mChatInfo.getType() == TIMConversationType.Group) {
                    params.put("GroupID", mChatInfo.getId());
                } else {
                    params.put("ToUserID", mChatInfo.getId());
                }

                HttpClient.get(getActivity(), Constants.GETSEARCHCHATRECORD, params, new CallBack<ChatDtssBean>() {
                    @Override
                    public void onSuccess(ChatDtssBean result) {
                        mDataSource.clear();
                        mDataMiMiSource.clear();
                        if (mChatInfo.isTopChat()){
                            mDataMiMiSource.addAll(result.List);
                        }else {
                            mDataSource.addAll(result.List);
                        }

                        String formAccount = SPUtil.getString(Constants.USERID);
                        List<String> list =  new ArrayList<>();
                        for (ChatDetailsBean chatDetailsBean : result.List) {
                            list.add(chatDetailsBean.getChatRecord_ID());
                        }
                        Map<String, Object> params2 = new HashMap<>();
                        params2.put("ChatRecordIDs",list.get(position));
                        params2.put("UserID", SPUtil.getString(Constants.USERID));
                        HttpClient.get(getActivity(), Constants.GETDELETECHATRECORD, params2,new CallBack<LoginBean>() {
                            @Override
                            public void onSuccess(LoginBean result) {
                                getChatRecordDetail(true);
                            }
                        });
                    }
                });*/
            }

            /**
             * 撤回  -------
             * @param position
             * @param msg
             */
            @Override
            public void onRevokeMessageClick(int position, ChatDetailsBean msg) {
                Map<String, Object> params = new HashMap<>();
                params.put("UserID", SPUtil.getString(Constants.USERID));
                params.put("Page", page2 + "");
                params.put("Rows", Rows + "");
                //密聊
                if (mChatInfo.isTopChat()){
                    params.put("RecordType", "1");
                }else {
                    params.put("RecordType", "0");
                }

                if (mChatInfo.getType() == TIMConversationType.Group) {
                    params.put("GroupID", mChatInfo.getId());
                } else {
                    params.put("ToUserID", mChatInfo.getId());
                }

                HttpClient.get(getActivity(), Constants.GETSEARCHCHATRECORD, params, new CallBack<ChatDtssBean>() {
                    @Override
                    public void onSuccess(ChatDtssBean result) {
                        /*mDataSource.clear();
                        mDataMiMiSource.clear();
                        if (mChatInfo.isTopChat()){
                            mDataMiMiSource.addAll(result.List);
                        }else {
                            mDataSource.addAll(result.List);
                        }*/

                      //  String formAccount = SPUtil.getString(Constants.USERID);
                        List<String> list =  new ArrayList<>();
                        for (ChatDetailsBean chatDetailsBean : result.List) {
                            list.add(chatDetailsBean.getChatRecord_ID() + "—" + chatDetailsBean.getChatRecord_Content());
                        }

                        UUID uuid = UUID.randomUUID();
                        MessagePackBean messagePackBean = new MessagePackBean();
                        messagePackBean.setID(uuid.toString());
                        messagePackBean.setGroupID("");
                        messagePackBean.setType(4);
                        messagePackBean.setRecordType(0);
                        messagePackBean.setMessage("");
                        messagePackBean.setSendId("");
                        messagePackBean.setReceiveId("");
                        messagePackBean.setID("");

                        messagePackBean.setChatRecordID(list.get(position));

                        Log.i("messagePackBean", messagePackBean.toString());

                        MainActivity.reliableClient.send("GetWithdrawChatRecord", messagePackBean);

                        Map<String, Object> params2 = new HashMap<>();
                        params2.put("ChatRecordID",list.get(position));
                        HttpClient.get(getActivity(), Constants.GETWITHDRAWCHATRECORD, params2,new CallBack<LoginBean>() {
                            @Override
                            public void onSuccess(LoginBean result) {
                               // getChatRecordDetail();
                                if (mChatInfo.isTopChat()){
                                    mDataMiMiSource.remove(msg);
                                }else {
                                    mDataSource.remove(msg);
                                }
                                messageListAdapter2.notifyDataSetChanged();
                            }
                        });
                    }
                });
            }
        });
    }

    //修改消息状态
    private void getUpdateChatRecordState() {
        Map<String, Object> params = new HashMap<>();
        params.put("UserID",SPUtil.getString(Constants.USERID));
        //普通消息 0
        if (mChatInfo.isTopChat()){
            params.put("ChatRecordType","1");
        }else {
            params.put("ChatRecordType","0");
        }
        if (mChatInfo.getType() == TIMConversationType.Group) {
            params.put("GroupID",mChatInfo.getId());
        } else {
            params.put("SendUserID",mChatInfo.getId());
        }
        HttpClient.get(getActivity(), Constants.GETUPDATECHATRECORDSTATE, params,new CallBack<LoginBean>() {
            @Override
            public void onSuccess(LoginBean result) {
                MessageEvent messageEvent2 = new MessageEvent();
                messageEvent2.setMessageKey(EventConstants.SENDMSG);
                EventBus.getDefault().post(messageEvent2);
            }
        });
    }


    private void sendMsg(ChatInfo mChatInfo, String input) {
        //随机数
        UUID uuid = UUID.randomUUID();
        MessagePackBean messagePackBean = new MessagePackBean();
        messagePackBean.setID(uuid.toString());
        if (mChatInfo.getType() == TIMConversationType.Group) {
            messagePackBean.setGroupID(mChatInfo.getId());
        } else {
            messagePackBean.setReceiveId(mChatInfo.getId());
            messagePackBean.setGroupID("");
        }
        //图片，文件
        if (string == 0) {
            //消息 类型
            messagePackBean.setType(0);
        } else if (string == 1){
            messagePackBean.setType(1);
            //语音消息
        }else if (string == 2){
            messagePackBean.setType(2);
        }else {
            messagePackBean.setType(3);
        }
        //普通消息 0   密聊消息是 1
        if (mChatInfo.isTopChat()){
            messagePackBean.setRecordType(1);
        }else {
            messagePackBean.setRecordType(0);
        }
        messagePackBean.setMessage(input);
        messagePackBean.setSendId(SPUtil.getString(Constants.USERID));


        if (!UItils.isNetWorkConnected()) {
            UItils.showToastSafe("网络已断开,请检查网络连接");
            return;
        }

                 //发送消息
                 if (mChatInfo.getType() == TIMConversationType.Group) {
                     MainActivity.reliableClient.send("SendGroupMessage", messagePackBean);
                 } else {
                     MainActivity.reliableClient.send("SendMessage", messagePackBean);
                 }
                 sendMegFlag = false;
                 chat_message_input.setText("");
                 inputLayout.hideSoftInput();
                 updateMsgList(input, messagePackBean.getID());



      /* if (null != HubConnectionUtils.hubConnection && HubConnectionUtils.hubConnection.getConnectionState() == HubConnectionState.CONNECTED) {
            //发送消息
            if (mChatInfo.getType() == TIMConversationType.Group) {
                HubConnectionUtils.hubConnection.send("SendGroupMessage", messagePackBean);
            } else {
                HubConnectionUtils.hubConnection.send("SendMessage", messagePackBean);
            }

            chat_message_input.setText("");
            inputLayout.hideSoftInput();
            updateMsgList(input, messagePackBean.getID());
            if (mChatInfo.getType() == TIMConversationType.Group) {
                MessageEvent messageEvent = new MessageEvent();
                messageEvent.setMessageKey(EventConstants.SENDMSG);
              //  EventBus.getDefault().post(messageEvent);
            }else {
              //  updateMsgList(input, messagePackBean.getID());
            }
        } else {
            //重新连接
            HubConnectionUtils.connection();
            UItils.showToastSafe("服务器连接断开，请重新发送");
        }*/
    }

    /**
     * 添加到聊天列表中
     * @param input
     * @param id
     */
    private void updateMsgList(String input, String id) {
        mDataSource2.clear();
        ChatDetailsBean chatDetailsBean = new ChatDetailsBean();
        chatDetailsBean.setChatRecord_Content(input);
        //消息发送状态
        chatDetailsBean.setStatus(com.whmnx.chitchat.constants.MessageInfo.MSG_STATUS_SENDING);
        //随机数
        chatDetailsBean.setID(id);
        //图片，文件
        if (string == 0) {
            //消息 类型
            chatDetailsBean.setChatRecord_Type(0);
        } else if (string == 1){
            chatDetailsBean.setChatRecord_Type(1);
        }else if (string == 2){
            chatDetailsBean.setChatRecord_Type(2);
        }else if (string == 3){ //文件消息
            chatDetailsBean.setChatRecord_Type(3);
        }else {
            chatDetailsBean.setChatRecord_Type(4);
        }
        String t = String.valueOf(System.currentTimeMillis() / 1000);
        chatDetailsBean.setCreateTime(UItils.timeStamp2Date(t));
        //发送人
        chatDetailsBean.setChatRecord_SendUserID(SPUtil.getString(Constants.USERID));
        //接收人
        if (mChatInfo.getType() == TIMConversationType.Group) {
            chatDetailsBean.setChatRecord_GroupID(mChatInfo.getId());
        } else {
            chatDetailsBean.setChatRecord_UserID(mChatInfo.getId());
        }
      //  chatDetailsBean.setChatRecord_UserID(id);
        mDataSource2.add(chatDetailsBean);
        if (mChatInfo.isTopChat()){
            mDataMiMiSource.addAll(mDataSource2);
        }else {
            mDataSource.addAll(mDataSource2);
        }
      //  messageListAdapter2.notifyItemRangeInserted(mDataSource.size() + 1, 0);
        //  notifyDataSetChanged();
        mChatLayout.getMessageLayout().scrollToEnd();
      //  messageListAdapter2.notifyDataSourceChanged(3, 0);
        BackgroundTasks.getInstance().postDelayed(new Runnable() {
            @Override
            public void run() {
                //发送失败
                if (id.equals(mDataSource2.get(0).getID()) && !sendMegFlag) {
                    mDataSource2.get(0).setStatus(com.whmnx.chitchat.constants.MessageInfo.MSG_STATUS_SEND_FAIL);
                    if (mChatInfo.isTopChat()) {
                        mDataMiMiSource.set(mDataMiMiSource.size() - 1, mDataSource2.get(0));
                        // messageListAdapter2.notifyDataSourceChanged(4, mDataMiMiSource.size()-1);
                    } else {
                        mDataSource.set(mDataSource.size() - 1, mDataSource2.get(0));
                        //  messageListAdapter2.notifyDataSourceChanged(4, mDataSource.size()-1);
                    }
                    messageListAdapter2.notifyDataSourceChanged(0, 0);
                }
            }
        }, 5000);
    }

    private void getChatRecordDetail(boolean isRefresh) {
        if (isRefresh) page = 1;
       // linearLayoutManager.scrollToPositionWithOffset(messageListAdapter2.getItemCount(), Integer.MIN_VALUE);
        //  rvChatDetails.setAdapter(messageListAdapter2);
        mChatLayout.getMessageLayout().setAdapter(messageListAdapter2);

        //   mChatLayout.getMessageLayout().scrollToEnd();

        Map<String, Object> params = new HashMap<>();
        params.put("UserID", SPUtil.getString(Constants.USERID));
        params.put("Page",page + "");
        params.put("Rows",Rows + "");
        //密聊
        if (mChatInfo.isTopChat()){
            params.put("RecordType", "1");
        }else {
            params.put("RecordType", "0");
        }

        if (mChatInfo.getType() == TIMConversationType.Group) {
            params.put("GroupID", mChatInfo.getId());
        } else {
            params.put("ToUserID", mChatInfo.getId());
        }
        imgList.clear();
        HttpClient.get(getActivity(), Constants.GETSEARCHCHATRECORD, params, new CallBack<ChatDtssBean>() {
            @Override
            public void onSuccess(ChatDtssBean result) {

                result2 = result;
             /*   mDataSource.clear();
                mDataMiMiSource.clear();
                if (mChatInfo.isTopChat()){
                    mDataMiMiSource.addAll(result.List);
                }else {
                    mDataSource.addAll(result.List);
                }*/
                if (isRefresh){
                    getUpdateChatRecordState();
                    mDataSource.clear();
                    mDataMiMiSource.clear();
                    refresh.finishRefresh(true);
                    if (mChatInfo.isTopChat()){
                        mDataMiMiSource.addAll(result.List);
                    }else {
                        mDataSource.addAll(result.List);
                    }
                    messageListAdapter2.notifyDataSetChanged();
                    page2 = page;
                }else {
                    if (result.List.size() > 0) {
                        refresh.finishLoadMore(true);
                        if (mChatInfo.isTopChat()){
                            mDataMiMiSource.addAll(result.List);
                        }else {
                            mDataSource.addAll(result.List);
                        }
                        messageListAdapter2.notifyDataSetChanged();
                        page2 = page;
                    }else {
                        refresh.finishLoadMoreWithNoMoreData();
                    }
                }
                page++;


                for (ChatDetailsBean chatDetailsBean : result.List) {
                    if (chatDetailsBean.getChatRecord_Type() == 1){
                        imgList.add(chatDetailsBean.getChatRecord_Content());
                    }
                }

             //   messageListAdapter2.notifyDataSetChanged();

                if (mChatInfo.getType() == TIMConversationType.Group) {
                    if (!TextUtils.isEmpty(result.Group.getGroup_Notice())) {
                        tvNotice.setVisibility(View.VISIBLE);
                        tvNotice.setText(result.Group.getGroup_Notice());
                    }
                    headTitle.setText(result.Group.getGroup_Name());
                }
                Constants.IMGLIST = imgList;
                Constants.IMGLIST2 = imgList2;

                String trim =  SPUtil.getString(Constants.TRIM);
                if (!TextUtils.isEmpty(trim) && result.List.size() > 0){
                   for (int i = 0; i < result.List.size(); i++) {
                       if (result.List.get(i).getChatRecord_Content().contains(trim)){
                           //  mChatLayout.getMessageLayout().scrollToPosition(i);
                             SPUtil.put(Constants.TRIM, "");
                             break;
                       }
                   }
               }else {
                    //自动滑动到底部
                  //  mChatLayout.getMessageLayout().scrollToPosition(result.List.size());
                }
            }
        });



       mChatLayout.getMessageLayout().setOnItemClickListener(new MessageLayout.OnItemClickListener() {
            @Override
            public void onMessageLongClick(View view, int position, ChatDetailsBean messageInfo) {
                mChatLayout.getMessageLayout().showItemPopMenu(position - 1, messageInfo, view);
            }

            @Override
            public void onUserIconClick(View view, int position, ChatDetailsBean messageInfo) {

            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        AudioPlayer.getInstance().stopPlay();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mChatLayout.exitChat();
    }


    private void showDialog() {
        Dialog dialogHead = new Dialog(getActivity(), R.style.ActionSheetDialogStyle);
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_head_portrait, null);

        view.findViewById(R.id.dialog_shoot).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent captureIntent = new Intent(getContext(), CameraActivity.class);
                captureIntent.putExtra(TUIKitConstants.CAMERA_TYPE, JCameraView.BUTTON_STATE_ONLY_CAPTURE);
                CameraActivity.mCallBack = new IUIKitCallBack() {
                    @Override
                    public void onSuccess(Object data) {
                        Uri contentUri = Uri.fromFile(new File(data.toString()));
                        MessageInfo msg = MessageInfoUtil.buildImageMessage(contentUri, true);
                        //发送图片消息
                        mChatLayout.sendMessage(msg, false);
                        dialogHead.dismiss();
                    }

                    @Override
                    public void onError(String module, int errCode, String errMsg) {
                        TUIKitLog.i("hhh", errMsg);
                    }
                };
                getContext().startActivity(captureIntent);
            }
        });
        view.findViewById(R.id.dialog_photo_album).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);

                getActivity().startActivityForResult(intent, 10000);
            }
        });
        view.findViewById(R.id.dialog_cancel).setOnClickListener(v -> dialogHead.dismiss());
        dialogHead.setContentView(view);
        Window window = dialogHead.getWindow();
        if (window == null) {
            return;
        }
        dialogHead.show();//显示对话框//设置Dialog从窗体底部弹出
        window.setGravity(Gravity.BOTTOM);
        //获取窗体的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        // lp.y = 20;//设置Dialog距离底部的距离
        //将属性设置给窗体
        window.setAttributes(lp);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
